#!/bin/bash
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================

set -e

BASEPATH=$(cd "$(dirname $0)"; pwd)
OUTPUT_PATH="${BASEPATH}/output"
BUILD_RELATIVE_PATH="build"
BUILD_PATH="${BASEPATH}/${BUILD_RELATIVE_PATH}/"

# print usage message
usage() {
  echo "Usage:"
  echo "  sh build.sh [-h | --help]"
  echo "              [--ascend_install_path=<PATH>]"
  echo ""
  echo "Options:"
  echo "    -h, --help        Print usage"
  echo "        --ascend_install_path=<PATH>"
  echo "                      Set ascend package install path, default /usr/local/Ascend/latest"
  echo ""
}

# parse and set options
checkopts() {
  if [ -n "$ASCEND_INSTALL_PATH" ]; then
    ASCEND_INSTALL_PATH="$ASCEND_INSTALL_PATH"
  else
    ASCEND_INSTALL_PATH="/usr/local/Ascend/latest"
  fi

  # Process the options
  parsed_args=$(getopt -a -o h -l help,ascend_install_path: -- "$@") || {
    usage
    exit 1
  }

  eval set -- "$parsed_args"

  while true; do
    case "$1" in
      -h | --help)
        usage
        exit 0
        ;;
      --ascend_install_path)
        ASCEND_INSTALL_PATH="$(realpath $2)"
        shift 2
        ;;
      --)
        shift
        break
        ;;
      *)
        echo "Undefined option: $1"
        usage
        exit 1
        ;;
    esac
  done

  if [ -n "$ASCEND_CUSTOM_OPP_PATH$ASCEND_CUSTOM_OPP_PATH" ]; then
    ASCEND_CUSTOM_OPP_PATH="$ASCEND_CUSTOM_OPP_PATH"
  else
    ASCEND_CUSTOM_OPP_PATH="$ASCEND_INSTALL_PATH/opp/vendors"
  fi
}

mk_dir() {
  local create_dir="$1"  # the target to make
  mkdir -pv "${create_dir}"
  echo "created ${create_dir}"
}

build_tf_parser() {
  echo "create build directory and build tf_parser";
  mk_dir "${BUILD_PATH}"
  cd "${BUILD_PATH}"
  cmake -D ASCEND_INSTALL_PATH=${ASCEND_INSTALL_PATH} \
        -D CMAKE_INSTALL_PREFIX=${OUTPUT_PATH} \
        -D ASCEND_CUSTOM_OPP_PATH=${ASCEND_CUSTOM_OPP_PATH} \
        ../tf_plugin

  make && make install
  if [ $? -ne 0 ]
  then
    echo "execute command: make && make install failed."
    return 1
  fi
  echo "tf_parser build success!"
}

main() {
  cd "${BASEPATH}"
  checkopts "$@"

  env
  g++ -v

  mk_dir ${OUTPUT_PATH}
  build_tf_parser || { echo "tf_parser build failed."; exit 1; }
  echo "---------------- tf_parser build finished ----------------"
}

main "$@"
